﻿using JTTD.Common.Attribute;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace JTTD.Common.Helper
{
    public static class DataTableHelper
    {
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dataTable) where T : new()
        {
            List<T> list = new List<T>();
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            if (dataTable.Rows.Count > 0)
            {
                foreach (DataRow row in dataTable.Rows)
                {
                    T model = new T();
                    foreach (var propertyInfo in propertyInfos)
                    {
                        string text=propertyInfo.GetCustomAttribute<ExcelAttribute>()?.Text;
                        var value = row[text];
                        if (value != null)
                        {
                            propertyInfo.SetValue(model, Convert.ChangeType(value, propertyInfo.PropertyType));
                        }
                    }
                    list.Add(model);
                }
            }
            return list;

        }
    }
}
